"""
Extension Security Manager for GSM Extension System

This module provides security validation and sandboxing capabilities
for GSM extensions to ensure safe loading and execution.
"""

from typing import Dict, List, Optional, Set, Any
from pathlib import Path
from dataclasses import dataclass
import logging


@dataclass
class SecurityValidationResult:
    """Result of extension security validation."""
    
    is_safe: bool
    reason: Optional[str] = None
    warnings: List[str] = None
    blocked_operations: List[str] = None
    
    def __post_init__(self):
        """Initialize lists if None."""
        if self.warnings is None:
            self.warnings = []
        if self.blocked_operations is None:
            self.blocked_operations = []


class ExtensionSecurityManager:
    """
    Basic security manager for extension validation.
    
    This is a placeholder implementation that can be extended with
    more sophisticated security checks as needed.
    """
    
    def __init__(self, logger: Optional[logging.Logger] = None):
        """Initialize security manager."""
        self._logger = logger or logging.getLogger(__name__)
        
        # Basic security configuration
        self._max_file_size_mb = 50
        self._allowed_file_extensions = {'.py', '.json', '.yaml', '.yml', '.txt', '.md'}
        self._blocked_imports = {'os.system', 'subprocess.call', 'eval', 'exec'}
        
        self._logger.debug("Extension security manager initialized")
    
    def validate_extension(self, extension_path: Path) -> SecurityValidationResult:
        """
        Perform basic security validation of extension package.
        
        Args:
            extension_path: Path to extension package
            
        Returns:
            SecurityValidationResult: Validation result
        """
        result = SecurityValidationResult(is_safe=True)
        
        try:
            # Check file sizes
            total_size = self._check_file_sizes(extension_path, result)
            
            # Check file types
            self._check_file_types(extension_path, result)
            
            # Basic content scanning (if enabled)
            self._scan_content(extension_path, result)
            
            if result.warnings:
                self._logger.warning(f"Security warnings for {extension_path.name}: {result.warnings}")
            
            return result
            
        except Exception as e:
            self._logger.error(f"Error during security validation: {str(e)}")
            return SecurityValidationResult(
                is_safe=False,
                reason=f"Security validation error: {str(e)}"
            )
    
    def _check_file_sizes(self, extension_path: Path, result: SecurityValidationResult) -> int:
        """Check file sizes in extension package."""
        total_size = 0
        
        try:
            for file_path in extension_path.rglob('*'):
                if file_path.is_file():
                    file_size = file_path.stat().st_size
                    total_size += file_size
                    
                    # Check individual file size
                    if file_size > self._max_file_size_mb * 1024 * 1024:
                        result.warnings.append(f"Large file detected: {file_path.name} ({file_size/1024/1024:.1f}MB)")
            
            # Check total package size
            total_size_mb = total_size / (1024 * 1024)
            if total_size_mb > self._max_file_size_mb * 2:
                result.warnings.append(f"Large extension package: {total_size_mb:.1f}MB")
            
        except Exception as e:
            result.warnings.append(f"Error checking file sizes: {str(e)}")
        
        return total_size
    
    def _check_file_types(self, extension_path: Path, result: SecurityValidationResult) -> None:
        """Check file types in extension package."""
        try:
            for file_path in extension_path.rglob('*'):
                if file_path.is_file():
                    suffix = file_path.suffix.lower()
                    
                    # Check for suspicious file types
                    if suffix and suffix not in self._allowed_file_extensions:
                        result.warnings.append(f"Unexpected file type: {file_path.name}")
                    
                    # Check for executable files
                    try:
                        if file_path.stat().st_mode & 0o111:  # Has execute permission
                            result.warnings.append(f"Executable file detected: {file_path.name}")
                    except Exception:
                        pass  # Ignore permission errors
            
        except Exception as e:
            result.warnings.append(f"Error checking file types: {str(e)}")
    
    def _scan_content(self, extension_path: Path, result: SecurityValidationResult) -> None:
        """Perform basic content scanning for suspicious patterns."""
        try:
            for file_path in extension_path.rglob('*.py'):
                if file_path.is_file():
                    try:
                        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                            content = f.read()
                            
                            # Check for blocked imports/operations
                            for blocked in self._blocked_imports:
                                if blocked in content:
                                    result.warnings.append(f"Suspicious import/operation in {file_path.name}: {blocked}")
                    
                    except Exception:
                        # Skip files that can't be read
                        pass
        
        except Exception as e:
            result.warnings.append(f"Error scanning content: {str(e)}")